<template>
  <div class="layout-padding">
    <el-row>
      <el-col :span="18">
        <el-input
          style="width: 30%"
          v-model="search.keyword"
          clearable
          placeholder="可输入名称搜索"
        />
        <el-button style="margin-left: 10px" type="primary" @click="searchFor"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="6" style="text-align: right">
        <el-button
          type="primary"
          @click="add({}, 'fa')"
          v-if="buttonDisplayOrNot(buttonCodes, 'dataAddBtn')"
          >新增</el-button
        >
      </el-col>
    </el-row>
    <el-table
      :data="tableData2"
      row-key="id"
      border
      style="width: 100%; margin-top: 15px"
      default-expand-all
      :header-cell-style="{
        background: '#E0E0E0',
        color: '#2B2B2B',
        fontWeight: 500
      }"
    >
      <el-table-column label="类型名称" prop="configValue" />
      <el-table-column label="字典类型" prop="name">
        <template #default="scope">
          <div>
            {{ scope.row.customizeFlag == 0 ? '系统默认' : '企业自定义' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" :width="320">
        <template #default="scope">
          <el-button
            v-if="
              scope.row.customizeFlag == 1 &&
              scope.row.level != 3 &&
              buttonDisplayOrNot(buttonCodes, 'dataAddBtn')
            "
            class="my-table__btn"
            size="default"
            plain
            @click="add(scope.row, 'item')"
            type="primary"
          >
            新增子项
          </el-button>
          <el-button
            v-if="
              scope.row.customizeFlag == 1 &&
              buttonDisplayOrNot(buttonCodes, 'dataEditBtn')
            "
            class="my-table__btn"
            color="#1962E0"
            size="default"
            plain
            @click="editDictionary(scope.row)"
            type="primary"
          >
            编辑
          </el-button>
          <el-button
            v-if="
              scope.row.customizeFlag == 1 &&
              buttonDisplayOrNot(buttonCodes, 'dataDeleteBtn')
            "
            class="my-table__btn"
            size="default"
            plain
            @click="deleteItem(scope.row)"
            type="danger"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <DictionariesDialog
      :dialogVisible="dialogVisible"
      :dialogForm="dialogForm"
      :dialogDetail="dialogDetail"
      @cancel="cancel"
      @submit="submit"
    >
    </DictionariesDialog>
  </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, defineAsyncComponent, onMounted, computed } from 'vue'
const DictionariesDialog = defineAsyncComponent(
  () => import('./DictionariesDialog.vue')
)
import { buttonDisplayOrNot } from '../../../utils/buttonBoolean'
import { getButtonListByRoleApi, dictionaryList } from '/@/api/publicApi'
import { deleteDictionary } from '/@/api/setting/index'
import { Session } from '/@/utils/storage'
import { loginOut } from '/@/api/login'
const menu = Session.get('menu')
const buttonCodes = ref<any>([])
onMounted(() => {
  getTableData()
  menu.forEach(async (element: any) => {
    if (element.menuUrl == '/setting/Dictionaries') {
      let res = await getButtonListByRoleApi({
        terminalType: 1,
        menuPid: element.id
      })
      res.data.forEach((item: any) => {
        buttonCodes.value.push(item.buttonCode)
      })
    }
  })
})

const dialogVisible = ref<boolean>(false) //弹窗是否出现
const dialogForm = {
  width: '25%',
  title: ''
}
const dialogDetail = ref<any>({})

//新增字典弹框
const add = (row: any, type: any) => {
  dialogForm.title = '新增'
  if (type == 'fa') {
    dialogDetail.value = { configType: 'device_type' }
  } else {
    dialogDetail.value = { configType: 'device_type', parentId: row.id }
  }
  dialogVisible.value = !dialogVisible.value
}
//编辑字典弹框
const editDictionary = (row: any) => {
  dialogForm.title = '编辑'
  dialogDetail.value = row
  dialogVisible.value = !dialogVisible.value
}

//弹框取消点击
const cancel = () => {
  dialogVisible.value = !dialogVisible.value
}
//弹框确定点击
const submit = () => {
  dialogVisible.value = !dialogVisible.value
  getTableData()
}
const search = ref({
  keyword: ''
})

const tableData = ref<any>([])
const tableData2 = computed(() => {
  let keyword = search.value.keyword
  if (keyword != '') {
    let treeData = tableData.value
    let handleTreeData: any = handleTree(treeData, keyword)
    setExpandRow(handleTreeData, 1)
    console.log(handleTreeData)
    return handleTreeData
  } else {
    setExpandRow(tableData.value, 1)
    return tableData.value
  }
})
// 初始化列表数据
const getTableData = async () => {
  let params = {
    keyword: '',
    configType: 'device_type'
  }
  let res = await dictionaryList(params)
  if (res.code == 0) {
    tableData.value = res.data
  }
}

const flag = ref(-1)
const handleTree = (treeData: any, searchValue: any) => {
  if (!treeData || treeData.length === 0) {
    return [] as any
  }
  const array = []
  for (let i = 0; i < treeData.length; i += 1) {
    let match = false
    for (let pro in treeData[i]) {
      if (typeof treeData[i][pro] == 'string') {
        match |= treeData[i][pro].includes(searchValue)
        if (match) break
      }
    }
    if (handleTree(treeData[i].children, searchValue).length > 0 || match) {
      if (treeData[i].type == 0 && match) {
        searchValue = ''
        array.push({
          ...treeData[i],
          children: handleTree(treeData[i].children, searchValue)
        })
      } else if (treeData[i].type == 1 && match) {
        if (flag.value == 0) {
          flag.value = 1
        }
        searchValue = ''
        array.push({
          ...treeData[i],
          children: handleTree(treeData[i].children, searchValue)
        })
        if (flag.value != 1) {
          searchValue = search
        }
      } else {
        array.push({
          ...treeData[i],
          children: handleTree(treeData[i].children, searchValue)
        })
      }
    }
  }
  return array
}

const setExpandRow = (handleTreeData: any, level: any) => {
  if (handleTreeData.length) {
    for (let i of handleTreeData) {
      i.level = level
      if (i.children) {
        setExpandRow(i.children, level + 1)
      }
    }
  }
}

const searchFor = () => {
  getTableData()
}

const deleteItem = (row: any) => {
  ElMessageBox.confirm('是否删除此字典?', '删除字典', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteDictionary(row.id).then((res) => {
        if (res.code == 0) {
          ElMessage({ type: 'success', message: '删除成功' })
          getTableData()
        }
      })
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '已取消' })
    })
}
</script>
<style lang="scss">
.col-divider {
  padding-left: 10px;

  .divider {
    height: 100%;
    padding-left: 10px;
  }
}
</style>
